// pages/search/search.js
let api = require("../../api/api.js")

Page({

  data: {
    carts:// 购物车内商品数据
    [
      // { id: 1, title: '华为 HUAWEI P10 全网通 4GB+64G 曜石黑 移动联通电信4GB手机', num: 4, price: 4500, selected: true },
      // { id: 2, title: 'Apple苹果 全网通 4GB+64G 曜石黑 移动联通电信4GB手机', num: 1, price: 6800, selected: true },
      // { id: 3, title: '小米 全网通 4GB+64G 曜石黑 移动联通电信4GB手机', num: 2, price: 4800, selected: true }
    ],
    //  hasList: tue,          // 列表是否有数据
    totalPrice: 0,           // 总价，初始为0
    selectAll: true,    // 全选状态，默认不全选

  },

  onLoad:function(){
    let that = this
    api.shoppingCart().then(res=>{
      console.log(res)
      that.setData({ carts: res.data })
      that.totlePrice()
      wx.hideLoading()
    })
  },

  //计算总价格
  totlePrice: function () {
    let carts = this.data.carts;
    let total = 0;
    let num = 0;
    for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
      if (carts[i].selected) {                   // 判断选中才会计算价格
        total += carts[i].course.shop_price;
      }
    }
    this.setData({
      totalPrice: total.toFixed(2)
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.totlePrice()
  },
  //选中反选
  selected: function (e) {
    const index = e.currentTarget.dataset.num;
    let carts = this.data.carts;
    let selectAll = this.data.selectAll;
    carts[index].selected = !carts[index].selected;
    let that = this;
    api.shoppingCartSelected(carts[index].course.id).then(res=>{
      console.log(res)
      that.setData({
        carts: carts,
        selectAll: selectAll
      });
      that.totlePrice();
    })
  },

  // 移除商品
  delete: function(e){
    const index = e.currentTarget.dataset.num;
    console.log(index)
    let that = this;
    wx.showModal({
      title: '删除',
      content: '确定移除课程？',
      success:function(){
        api.shoppingCartDelete(that.data.carts[index].course.id).then(res=>{
          //从数组中移除元素
          that.removeItem(index)      
          wx.showToast({
            title: '移除成功',
            icon: 'none',
            duration: 1000
          })
        })
      }
    })

  },

  // 移除购物车列表中的元素
  removeItem:function(index){
    let tempCart = [];
    for(var i = 0; i < this.data.carts.length; i++){
      if(i === index){
        continue
      }
      tempCart.push(this.data.carts[i])
    }
    this.setData({ carts: tempCart })
  },

  // 去结算
  toPay:function(){
    let flag = false
    for(var i = 0; i < this.data.carts.length; i ++){
      if(this.data.carts[i].selected){
        flag = !flag //有被选中的
        break;
      }
    }
    if(!flag){
      wx.showToast({
        title: '请选中一个以上课程',
        icon: 'none',
        duration: 3000
      })
      return
    }
    let that = this
    wx.setStorageSync('carts', that.data.carts)
    wx.navigateTo({
      url: '../payConfirm/payConfirm?totalPrice='+that.data.totalPrice
    })

  }
  

})

